package com.wpml.juc;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Date 2021-05-21
 * @Author wangpei
 **/
public class ExecutorTest {

    static final Unsafe UNSAFE;

    static int num = 0;

    static final long a_offset;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            UNSAFE = (Unsafe) theUnsafe.get(null);
            a_offset = UNSAFE.staticFieldOffset(ExecutorTest.class.getDeclaredField("num"));
        } catch (Exception e) {
            throw new RuntimeException();
        }

    }

    public static void incr() {
        for (;;) {
            int t = num;
            if (UNSAFE.compareAndSwapInt(ExecutorTest.class,a_offset, t, ++t)) {
                break;
            }
            Thread.yield(); // 让出cpu
        }
    }

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();

        for (int i = 0; i < 1000; i++) {
            executorService.execute(() -> incr());
        }

        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.SECONDS);

        System.out.println(num);
//        test(args);
    }

    private static void test(String[] args) {
        out:
        if (1==1) {
            System.out.println(1);
            if (args.length != 0) {
                return;
            } else {
//                break out;
            }

        }

        System.out.println(2);
    }
}
